<template>
    <!-- 手机验证码 -->
    <el-input placeholder="请输入短信验证码" v-model="model" v-bind="$attrs" class="input">
        <template #append>
            <el-link :disabled="!phone" @click="showImage" v-if="!restTime" class="send">发送</el-link>
            <span v-else>{{ restTime }}S</span>
        </template>
    </el-input>

    <el-dialog title="发送短信验证码" width="400px" v-model="visible" destroy-on-close append-to-body>
        <el-form class="form" :model="imageForm" ref="imageFormRef" :key="key">
            <el-form-item label="图形验证码" required prop="imageCode">
                <el-input placeholder="请输入图形验证码" autofocus v-model="imageForm.imageCode" class="input">
                    <template #append>
                        <img :src="image" class="img cursor-pointer" @click="regenerate" />
                    </template>
                </el-input>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button type="primary" icon="Checked" @click="sendPhoneMessage">发送短信</el-button>
        </template>
    </el-dialog>
</template>
<script setup>
import { v4 } from "uuid";

const visible = ref(false);
const image = ref();
const key = ref();
const imageForm = ref({});
const imageFormRef = ref();
const restTime = ref(0);
const model = defineModel();
let timer;
const { phone } = defineProps({
    phone: String,
});

function regenerate() {
    key.value = v4();
    imageForm.value = {};
    app.https.get("/sys/image-code/generate", { key: key.value }).then((resp) => {
        image.value = resp;
    });
}

function showImage() {
    key.value = v4();
    imageForm.value = {};
    app.https.get("/sys/image-code/generate", { key: key.value }).then((resp) => {
        image.value = resp;
        visible.value = true;
    });
}

function sendPhoneMessage() {
    imageFormRef.value.validate((res) => {
        if (!res) {
            return;
        }

        app.https.get("/sys/phone-message/send", { phone, imageKey: key.value, imageCode: imageForm.value.imageCode }).then((resp) => {
            app.success("短信发送成功");
            restTime.value = 60;
            timer = setInterval(() => {
                if (restTime.value <= 0) {
                    clearInterval(timer);
                    return;
                }
                restTime.value--;
            }, 1000);
        });
    });
}
</script>

<style lang="scss" scoped>
.send {
    width: 80px;
}

.input {
    :deep() {
        .el-input-group__append,
        .el-input-group__prepend {
            padding: 0px;
        }
    }
}
</style>
